package model.data.container;

/**
 * AccountContainer.java
 * Purpose: A container to hold account objects.
 * 
 * @author Jan Harm Van Enk
 * @version 0.2 24/01/2012
 */

import java.util.ArrayList;
import java.util.List;

import model.Account;
import model.data.AccountStore;
import model.data.DuplicateRecordException;
import model.data.RecordNotFoundException;

public class AccountContainer implements AccountStore {
	/* List of accounts */
	private ArrayList<Account> accounts;
	
	/** Constructs a new account container */
	public AccountContainer() {
		 this.accounts = new ArrayList<Account>();
	}
	
	/** Writes an account to the container */
	public void write(Account account) throws DuplicateRecordException {
		if (this.getById(account.getId()) == null) {
			this.accounts.add(account);
		}
		else
		{
			throw new DuplicateRecordException();
		}
	}

	/** Updates an existing account in the container */
	public void update(Account account) {
		// TODO update logic
		// currently impossible due to referencing issue
	}
	
	/** Deletes an existing account from the container */
	public void delete(Account account) throws RecordNotFoundException {
		if (this.getById(account.getId()) != null) {
			this.accounts.remove(account);
		}
		else
		{
			throw new RecordNotFoundException();
		}
	}
	
	/** Returns the number of items in the container */
	public int getCount() {
		return this.accounts.size();
	}

	/** Returns an account from the container with a specific id */
	public List<Account> getById(long id) {
		ArrayList<Account> accounts;
		
		// Create list
		accounts = new ArrayList<Account>();
		
		// Fill list
		for (Account account : this.accounts) {
			if(account.getId() == id) {
				accounts.add(account);
			}
		}
		
		//Return the results
		return accounts;
	}

	/** Returns an account from the container with a specific user name */
	public List<Account> getByUserName(String userName) {
		ArrayList<Account> accounts;
		
		// Create list
		accounts = new ArrayList<Account>();
		
		// Fill list
		for (Account account : this.accounts){
			if(account.getUserName().equals(userName)) {
				accounts.add(account);
			}
		}
		
		//Return the results
		return accounts;
	}
}